import "./reset.css";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { TerminalItem } from "./types";
import type { FormItemProps } from "./types";
import { h, computed, ref, type Ref, reactive, onMounted } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import editForm from "../form/index.vue";
import { ElMessageBox } from "element-plus";

export function useTerminal(tableRef: Ref) {
  const form = reactive({
    terminalName: "",
    terminalId: "",
    model: "",
    machineType: "",
    operatingEnv: "",
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = ref();
  const dataList = ref<TerminalItem[]>([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  //列表
  const columns = [
    {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "型号",
      prop: "model",
      minWidth: 130
    },
    {
      label: "机种",
      prop: "machineType",
      minWidth: 130
    },
    {
      label: "运行环境",
      prop: "operatingEnv",
      minWidth: 130
    },
    {
      label: "程序类型",
      prop: "programType",
      minWidth: 130
    },
    {
      label: "固件版本",
      prop: "firmwareVersion",
      minWidth: 130
    },
    {
      label: "协议版本",
      prop: "protocolVersion",
      minWidth: 130
    },
    {
      label: "功能特性",
      prop: "features",
      minWidth: 180,
      cellRenderer: scope => {
        return (
          <div class="flex flex-wrap gap-1">
            {(scope.row.Features ?? []).map((feature, index) => {
              // 根据特性名称确定标签颜色
              const color =
                feature === "摄像头" || feature === "GPS" || feature === "SIM"
                  ? "primary"
                  : feature === "屏幕" || feature === "UI" || feature === "TTS"
                    ? "success"
                    : feature === "陀螺仪" || feature === "个呼"
                      ? "warning"
                      : "info";
              return (
                <el-tag key={index} type={color} size="small">
                  {feature}
                </el-tag>
              );
            })}
          </div>
        );
      }
    },
    {
      label: "图像URL",
      prop: "imageUrl",
      minWidth: 180
    },
    {
      label: "下载URL",
      prop: "downloadUrl",
      minWidth: 180
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 150
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];

  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  //删除
  function handleDelete(row) {
    http
      .request("delete", changeHttpLink(`/api/Terminal/${row.Id}`), {
        data: row.Id
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(`您删除了终端编号为${row.Id}的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  //下载
  function handleDownloadApp(row) {
    message(`下载终端${row.model}的APP`, { type: "info" });
    // 这里可以添加实际的下载逻辑
    window.open(row.downloadUrl, "_blank");
  }
  //分页大小变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }
  //处理变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }
  //多选框变化
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }
  //多选框反选
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  //批量删除
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const listIds = curSelected.map(item => item.id);

    ElMessageBox.confirm(
      `是否确认删除选中的${listIds.length}条数据`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      }
    )
      .then(() => {
        loading.value = true;
        http
          .post(changeHttpLink("/api/Terminal/BatchDelete"), {
            data: { ids: listIds }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已删除选中的${listIds.length}条数据`, {
                type: "success"
              });
              tableRef.value.getTableRef().clearSelection();
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }
  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  //获取、搜索终端列表
  function onSearch() {
    loading.value = true;
    const params = {
      PageIndex: pagination.currentPage,
      pageSize: pagination.pageSize,
      OrderBy: form.OrderBy,
      IsDesc: false,
      SearchTerm: form.SearchTerm,
      Model: form.model,
      MachineType: form.machineType,
      OperatingEnv: form.operatingEnv
    };
    console.log(params);
    http
      .get(changeHttpLink("/api/Terminal"), {
        data: params
      })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          const newData = res.Data.Items;
          // 根据字段值动态生成Features数组
          const processedData = newData.map(item => {
            const features = [];
            // 映射字段到特性名称
            const featureMap = [
              { field: "hasCam", name: "摄像头", color: "primary" },
              { field: "hasScreen", name: "屏幕", color: "success" },
              { field: "hasUI", name: "UI", color: "success" },
              { field: "hasGps", name: "GPS", color: "primary" },
              { field: "hasGyro", name: "陀螺仪", color: "warning" },
              { field: "hasSim", name: "SIM", color: "primary" },
              { field: "p2pAuto", name: "个呼", color: "warning" },
              { field: "tts", name: "TTS", color: "success" }
            ];

            // 检查每个字段的值，如果为1则添加到特性列表
            Object.entries(featureMap).forEach(([field, name]) => {
              if (item[field] === 1) {
                features.push(name);
              }
            });

            return {
              ...item,
              Features: features
            };
          });

          dataList.value = processedData;
          console.log(dataList.value);
          pagination.total = res.Data.TotalCount;
          setTimeout(() => {
            loading.value = false;
          }, 300);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //新增、修改
  function openDialog(title, row: any) {
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}终端`,
      props: {
        formInline: {
          Id: row?.Id ?? 0,
          TenantId: row?.TenantId ?? 0,
          DealerId: row?.DealerId ?? 0,
          Model: row?.Model ?? "",
          Type: row?.Type ?? "",
          Runtime: row?.Runtime ?? "",
          AppType: row?.AppType ?? "",
          AppVer: row?.AppVer ?? "",
          PVer: row?.PVer ?? 0,
          HasCam: row?.HasCam ?? 0,
          HasScreen: row?.HasScreen ?? 0,
          HasUI: row?.HasUI ?? 0,
          HasGps: row?.HasGps ?? 0,
          HasGyro: row?.HasGyro ?? 0,
          HasSim: row?.HasSim ?? 0,
          P2PAuto: row?.P2PAuto ?? 0,
          Tts: row?.Tts ?? 0,
          ImageUrl: row?.ImageUrl ?? "",
          DlUrl: row?.DlUrl ?? "",
          Comment: row?.Comment ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, { ref: formRef, formInline: null, title: title }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了终端Id为【${curData.Id}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              Id: 0,
              TenantId: curData?.TenantId ?? 0,
              DealerId: curData?.DealerId ?? 0,
              Model: curData?.Model ?? "",
              Type: curData?.Type ?? "",
              Runtime: curData?.Runtime ?? "",
              AppType: curData?.AppType ?? "",
              AppVer: curData?.AppVer ?? "",
              PVer: curData?.PVer ?? 0,
              HasCam: curData?.HasCam ?? 0,
              HasScreen: curData?.HasScreen ?? 0,
              HasUI: curData?.HasUI ?? 0,
              HasGps: curData?.HasGps ?? 0,
              HasGyro: curData?.HasGyro ?? 0,
              HasSim: curData?.HasSim ?? 0,
              P2PAuto: curData?.P2PAuto ?? 0,
              Tts: curData?.Tts ?? 0,
              ImageUrl: curData?.ImageUrl ?? "",
              DlUrl: curData?.DlUrl ?? "",
              Comment: curData?.Comment ?? ""
            };
            console.log("已上传", formData);
            if (title == "创建") {
              http
                .post(changeHttpLink("/api/Terminal"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else if (title !== "创建") {
              formData.Id = id;
              http
                .request("put", changeHttpLink(`/api/Terminal/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  console.log("res", res);
                  if (res.Success) {
                    chores();
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  message(err.message, { type: "error" });
                  loading.value = false;
                });
            }
          }
        });
      }
    });
  }
  //修改
  function handleUpdate(row) {
    console.log(row);
  }
  // 设备检测
  function deviceDetection() {
    return window.innerWidth <= 1024;
  }
  onMounted(() => {
    // 初始化加载数据
    onSearch();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleDownloadApp,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
